package com.jintao.springboot.distributelock.redislock.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;

import java.util.Collections;

/**
 * @author jinjueYang
 * @description
 * @date 2019/10/26 14:09
 */
@Component
public class RedisUtil {

    @Autowired
    private JedisPool jedisPool;

    private static final String LOCK_SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";
    private static final Long RELEASE_SUCCESS = 1L;


    /**
     * 尝试获取分布式锁
     *
     * @param lockKey    我们使用key来当锁，因为key是唯一的
     * @param requestId  每个请求的唯一id作为值
     * @param expireTime 过期时间 单位毫秒
     * @return 是否获取成功
     */
    public boolean tryAquireDistributedLock(String lockKey, String requestId, int expireTime) {
        if (-1 == expireTime) {
            //不允许设置为永久有效,默认5秒
            expireTime = 5000;
        }
        String result = jedisPool.getResource().set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
        if (LOCK_SUCCESS.equals(result)) {
            return true;
        }
        return false;
    }

    /**
     * 释放分布式锁
     *
     * @param lockKey   锁
     * @param requestId 请求标识
     * @return 是否释放成功
     */
    public boolean releaseDistributedLock(String lockKey, String requestId) {

        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Object result = jedisPool.getResource().eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
        if (RELEASE_SUCCESS.equals(result)) {
            return true;
        }
        return false;
    }
}
